<?php

namespace App\Http\Controllers\Mp;

use App\Http\Resources\Mp\BookOrderResource;
use App\Models\BookOrder;
use App\Models\BookRule;
use App\Services\BookOrderService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Class BookOrderController
 * @package App\Http\Controllers\Mp
 * @author zjw
 */
class BookOrderController extends BaseController
{
    /**
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $orders = BookOrder::belongToUser()->isNormalOrChildren()
            ->with(['rule', 'children:id,name', 'user:id,name'])->orderBy("created_at",'desc')
            ->statusIs($request->status)->paginate(10);
        return BookOrderResource::collection($orders);
    }

    /**
     * @param Request $request
     * @return array|mixed
     * @throws \Throwable
     */
    public function store(Request $request)
    {
        try {
            return DB::transaction(function() use ($request) {
                $user = \Auth::user();
                $breakfastIds = $request->breakfastIds;
                $dinnerIds = $request->dinnerIds;
                $lunchIds = $request->lunchIds;
                if ($request->children_id) {
                    $rules = BookRule::whereIn('id', array_merge($breakfastIds,$dinnerIds,$lunchIds))->where('school_id', $user->school_id)->get();
                } else {
                    $rules = BookRule::whereIn('id', array_merge($breakfastIds,$dinnerIds,$lunchIds))->toUser()->get();
                }
                foreach ($rules as $rule) {
                    if ($request->children_id) {
                        if ($user->canBookByRule($rule, $request->children_id)) {
                            BookOrderService::generateChildrenOrder($user, $rule, $request->children_id);
                        }
                    } else {
                        if ($user->canBookByRule($rule)) {
                            BookOrderService::generateOrder($user, $rule);
                        }
                    }
                }
                return [];
            });
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    /**
     * @param Request $request
     * @param $id
     * @return BookOrderResource|array
     */
    public function update(Request $request,$id)
    {
        $order = BookOrder::belongToUser()->where("id",$id)->first();
        if ($order && $order->cancel()) {
            return new BookOrderResource($order);
        }
        return $this->fail('取消失败');
    }
}
